<template>
  <el-card class="page-container">
    <template #header>
      <div class="order-header">
        <div class="order-number">
          订单号:
          <span>
            {{ orderDetailInfo.number }}
          </span>
          <div class="order-status" :class="{
            status1: [
              OrderStatusEnum.TO_BE_CONFIRMED,
              OrderStatusEnum.TO_BE_DELIVERED,
              OrderStatusEnum.IN_DELIVERY,
            ].includes(orderDetailInfo.status),
          }">
            {{ getOrderStatus(orderDetailInfo.status) }}
          </div>
        </div>
        <div class="order-time">下单时间：{{ orderDetailInfo.orderTime }}</div>
      </div>
    </template>
    <div class="order-middle">
      <div class="user-info">
        <div class="user-info-box">
          <div class="user-name">
            <label>用户名</label>
            <span>{{ orderDetailInfo.consignee }}</span>
          </div>
          <div class="user-phone">
            <label>手机号</label>
            <span>{{ orderDetailInfo.phone }}</span>
          </div>
          <div v-if="[2, 3, 4, 5].includes(orderDetailInfo.status)" class="user-getTime">
            <label>{{ orderDetailInfo.status === 5 ? '送达时间' : '预计送达时间' }}</label>
            <span>{{
              orderDetailInfo.status === 5 ? orderDetailInfo.deliveryTime : orderDetailInfo.estimatedDeliveryTime
            }}</span>
          </div>
          <div class="user-address">
            <label>地址</label>
            <span>{{ orderDetailInfo.address }}</span>
          </div>
          <div class="user-remark" :class="{ orderCancel: orderDetailInfo.status === 6 }">
            <label>{{ orderDetailInfo.status === 6 ? '取消原因' : '备注' }}</label>
            <span>{{
              orderDetailInfo.status === 6
                ? orderDetailInfo.cancelReason || orderDetailInfo.rejectionReason
                : orderDetailInfo.remark
            }}</span>
          </div>
        </div>
      </div>

      <div class="dish-info">
        <label>菜品</label>
        <div class="dish-list">
          <div v-for="(item, index) in orderDetailInfo.orderDetailList" :key="index" class="dish-item">
            <div class="dish-item-box">
              <span class="dish-name">{{ item.name }}</span>
              <span class="dish-num">x{{ item.number }}</span>
            </div>
            <span class="dish-price">￥{{ item.amount ? item.amount.toFixed(2) : '' }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="order-amount">
      <div class="amount-info">
        <label>费用</label>
        <div class="amount-list">
          <div class="dish-amount">
            <span class="amount-name">菜品小计：</span>
            <span class="amount-price">￥{{
              decimalsReplenish(orderDetailInfo.amount - orderDetailInfo.deliveryAmount - orderDetailInfo.packAmount)
            }}</span>
          </div>
          <div class="send-amount">
            <span class="amount-name">派送费：</span>
            <span class="amount-price">￥{{ orderDetailInfo.deliveryAmount ?
              decimalsReplenish(orderDetailInfo.packAmount) :
              '' }}</span>
          </div>
          <div class="package-amount">
            <span class="amount-name">打包费：</span>
            <span class="amount-price">￥{{ orderDetailInfo.packAmount ? decimalsReplenish(orderDetailInfo.packAmount) :
              ''
            }}</span>
          </div>
          <div class="all-amount">
            <span class="amount-name">合计：</span>
            <span class="amount-price">￥{{ orderDetailInfo.amount ? decimalsReplenish(orderDetailInfo.amount) : ''
            }}</span>
          </div>
          <div class="pay-status">
            <span class="pay-name">支付状态：</span>
            <span class="pay-value">{{ getPayStatus(orderDetailInfo.payStatus) }}</span>
          </div>
          <div class="pay-type">
            <span class="pay-name">支付方式：</span>
            <span class="pay-value">{{ getPayMethod(orderDetailInfo.payMethod) }}</span>
          </div>
          <div class="pay-time">
            <span class="pay-name">支付时间：</span>
            <span class="pay-value">{{ orderDetailInfo.checkoutTime }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单评价列表 -->
    <div v-if="getOrderStatus(orderDetailInfo.status) === '已完成'" class="order-comment">
      <label>评论</label>
      <el-table :data="orderCommentList" style="width: 100%; margin-top: 12px" border stripe class="comment-table">
        <!-- 表格标题栏 -->
        <el-table-column label="用户" prop="userName" width="180" />
        <el-table-column label="评论内容" prop="comment" min-width="300" />
        <el-table-column label="评论时间" prop="commentTime" width="180" />
      </el-table>
    </div>

    <div class="order-footer" v-if="userStore.rule !== 'admin'">
      <el-button v-if="isActionButtonVisible(orderDetailInfo.status, 'reject')" @click="cancelHandle">拒 单</el-button>
      <el-button v-if="isActionButtonVisible(orderDetailInfo.status, 'accept')" type="primary" @click="statusHandle">接
        单</el-button>
      <el-button @click="router.back()">返 回</el-button>
      <el-button v-if="isActionButtonVisible(orderDetailInfo.status, 'deliver')" type="primary" @click="statusHandle">派
        送</el-button>
      <el-button v-if="isActionButtonVisible(orderDetailInfo.status, 'complete')" type="primary" @click="statusHandle">完
        成</el-button>
      <el-button v-if="isActionButtonVisible(orderDetailInfo.status, 'cancel')" type="danger"
        @click="cancelHandle">取消订单</el-button>
    </div>
    <div class="order-footer" v-else>
      <el-button @click="router.back()">返 回</el-button>
    </div>
  </el-card>
  <!-- 取消弹窗 -->
  <el-dialog v-model="cancelDialogVisible" :title="dialogTitle + '订单'" width="500"
    :before-close="() => ((cancelDialogVisible = false), (reason = ''))" :show-close="false">
    <el-form>
      <el-form-item :label="dialogTitle + '原因'" prop="label">
        <el-select v-model="reason" :placeholder="'请选择' + dialogTitle + '原因'">
          <el-option v-for="item in dialogTitle === '取消' ? cancelrReasonList : cancelOrderReasonList" :key="item.value"
            :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="reason === '其他原因'" label="其他原因:">
        <el-input v-model="remark" type="textarea" :placeholder="'请填写您' + dialogTitle + '的原因（限20字内）'" maxlength="20" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="(cancelDialogVisible = false), (reason = '')">取消</el-button>
        <el-button type="primary" @click="submitHandle">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  cancelOrderAPI,
  completeOrderAPI,
  confirmOrderAPI,
  deliveryOrderAPI,
  getOrderDetailAPI,
  rejectOrderAPI,
  getCommentListAPI,
} from '@/api/business/ordet'
import { OrderDetailInfo } from '@/types/order'
import { ElMessage } from 'element-plus'
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  cancelrReasonList,
  cancelOrderReasonList,
  DialogTitleEnum,
  getOrderStatus,
  OrderStatusEnum,
  isActionButtonVisible,
  getPayStatus,
  getPayMethod,
} from './constant'
import { decimalsReplenish } from '@/utils/index'
import { useUserStore } from '@/stores/userStore'
import { getAdminOrderDetailAPI, getAdminCommentListAPI } from '@/api/admin/ordet'
import type { CommentItem } from '@/types/comments'
const route = useRoute()
const router = useRouter()
const orderId = computed(() => Number(route.query.id))
// 订单详细信息
const orderDetailInfo = ref({} as OrderDetailInfo)

const cancelDialogVisible = ref(false) //取消，拒单弹窗
const dialogTitle = ref('') //取消，拒绝弹窗标题
const reason = ref('') //取消，拒绝原因
const remark = '' //自定义原因
const userStore = useUserStore()
const getOrderDetail = async () => {
  try {
    if (userStore.rule === 'admin') {
      let { data } = await getAdminOrderDetailAPI(orderId.value)
      orderDetailInfo.value = data
    } else {
      let res = await getOrderDetailAPI(orderId.value)
      orderDetailInfo.value = res.data
    }
  } catch (error) {
    console.log(error)
  }
}
const orderCommentList = ref<CommentItem[]>([])
const page = ref({
  page: 1,
  pageSize: 10
})
const total = ref(0)
const getOrderCommentList = async () => {
  try {
    if (userStore.rule === 'admin') {
      let { data } = await getAdminCommentListAPI({
        pageQueryDTO: {
          page: page.value.page,
          pageSize: page.value.pageSize
        },
        orderId: orderId.value,
      })
      orderCommentList.value = data.records
      total.value = data.total
    } else {
      let { data } = await getCommentListAPI({
        pageQueryDTO: {
          page: page.value.page,
          pageSize: page.value.pageSize
        },
        orderId: orderId.value,
      })
      orderCommentList.value = data.records
      total.value = data.total
    }


  } catch (error) {
    console.log(error)
  }
}
const statusHandle = async () => {
  try {
    if (orderDetailInfo.value.status === OrderStatusEnum.TO_BE_CONFIRMED) {
      await confirmOrderAPI(orderId.value)
      ElMessage.success('接单成功')
    } else if (orderDetailInfo.value.status === OrderStatusEnum.TO_BE_DELIVERED) {
      await deliveryOrderAPI(orderId.value)
      ElMessage.success('开始派送')
    } else if (orderDetailInfo.value.status === OrderStatusEnum.IN_DELIVERY) {
      await completeOrderAPI(orderId.value)
      ElMessage.success('订单已完成')
    }
  } catch (error) {
    ElMessage.error(error || '操作失败')
  }
  router.back()
}
// 取消/拒绝订单
const cancelHandle = () => {
  if (orderDetailInfo.value.status === OrderStatusEnum.TO_BE_CONFIRMED) {
    dialogTitle.value = DialogTitleEnum.REJECT
  } else {
    dialogTitle.value = DialogTitleEnum.CANCEL
  }
  cancelDialogVisible.value = true
}
// 确认取消/拒绝原因
const submitHandle = async () => {
  try {
    if (dialogTitle.value === DialogTitleEnum.CANCEL) {
      await cancelOrderAPI({ id: orderId.value, cancelReason: reason.value })
      ElMessage.success('取消成功')
    } else {
      await rejectOrderAPI({
        id: orderId.value,
        rejectionReason: reason.value,
      })
      ElMessage.success('拒绝成功')
    }
    cancelDialogVisible.value = false
    router.back()
  } catch (error) {
    ElMessage.error(error || '操作失败')
  }
}
onMounted(() => {
  getOrderDetail()
  getOrderCommentList()
})
</script>
<style scoped lang="scss">
.order-header {
  line-height: 28px;
  font-size: 14px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 20px;

  .order-number {
    display: flex;

    span {
      margin: 0 10px;
      font-weight: 700;
    }

    .order-status {
      width: 60px;
      height: 30px;
      color: #fff;
      border-radius: 20px;
      background-color: #000;
      text-align: center;
    }

    .status1 {
      background-color: #fd3333;
    }
  }
}

label {
  width: 120px;
  box-sizing: border-box;
}

.order-middle {
  .user-info {
    min-height: 120px;
    background: #fbfbfa;
    display: flex;
    margin-top: 20px;
    padding: 20px 40px;
    color: #333;

    .user-info-box {
      display: flex;
      flex-wrap: wrap;

      .user-name,
      .user-phone,
      .user-getTime,
      .user-address,
      .user-remark {
        display: flex;
        flex: 50%;
        align-items: center;
      }

      .orderCancel {
        div {
          padding: 0 10px;
          background-color: #e5e4e4;
        }

        span {
          color: #f56c6c;
        }
      }
    }
  }

  .dish-info {
    min-height: 80px;
    display: flex;
    flex-wrap: wrap;
    padding: 20px 40px;
    border-bottom: 1px solid #e7e6e6;

    .dish-list {
      flex: 80%;
      display: flex;
      flex-wrap: wrap;

      .dish-item {
        display: inline-block;
        width: 300px;
        margin-bottom: 14px;
        color: #333;

        .dish-item-box {
          display: inline-block;
          width: 120px;
        }
      }
    }
  }
}


.order-amount {
  border-bottom: 1px solid #e7e6e6;

  .amount-info {
    min-height: 120px;
    display: flex;
    flex-wrap: wrap;
    padding: 20px 40px;

    .amount-label {
      color: #666;
      margin-right: 65px;
    }

    .amount-list {
      flex: 80%;
      display: flex;
      flex-wrap: wrap;
      color: #333;

      .dish-amount,
      .package-amount,
      .pay-status,
      .pay-time {
        display: inline-block;
        width: 300px;
        margin-bottom: 14px;
      }

      .send-amount,
      .all-amount,
      .pay-type {
        display: inline-block;
        flex: 50%;
        padding-left: 10%;
      }

      .package-amount {
        .amount-name {
          margin-right: 14px;
        }
      }

      .all-amount {
        .amount-name {
          margin-right: 24px;
        }

        .amount-price {
          color: #f56c6c;
        }
      }

      .send-amount {
        .amount-name {
          margin-right: 10px;
        }
      }
    }
  }
}

.order-comment {
  padding: 20px 40px;
}

.order-footer {
  margin: 20px 0;
  float: right;
}
</style>
